package org.oc.qaq.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.oc.qaq.dto.FileDTO;
import org.oc.qaq.dto.FilePageQueryDTO;
import org.oc.qaq.exception.UnsupportedFileTypeException;
import org.oc.qaq.result.PageResult;
import org.oc.qaq.result.Result;
import org.oc.qaq.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/v1/files")
@Tag(name = "文件相关接口")
public class FileController {

    @Autowired
    private FileService fileService;

    @Operation(summary = "列出用户拥有的所有文件")
    @GetMapping
    public PageResult<?> getFiles(FilePageQueryDTO query) {
        return fileService.listFiles(query);
    }

    @Operation(summary = "文件创建接口")
    @PostMapping
    public Result<?> createOrUpdate(@RequestBody FileDTO fileDTO) throws IOException {
        fileService.createOrUpdate(fileDTO);
        return Result.success();
    }

    @Operation(summary = "文件更新接口")
    @PutMapping
    public Result<?> update(@RequestBody FileDTO fileDTO) throws IOException {
        fileService.createOrUpdate(fileDTO);
        return Result.success();
    }

    @Operation (summary = "文件重命名")
    @PutMapping("/rename/{id}/{newName}")
    public Result<?> rename(@PathVariable String newName, @PathVariable String id) {
        fileService.rename(newName, id);
        return Result.success();
    }

    @Operation(summary = "文件上传")
    @PostMapping("/upload")
    public Result<String> upload(@RequestPart("file") MultipartFile file,
                                 @RequestParam("tagIds") List<Long> tagIds
    ) throws UnsupportedFileTypeException, IOException {
        return fileService.upload(file, tagIds);
    }

    @Operation(summary = "文件下载")
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> download(@PathVariable String id) throws IOException {
        return fileService.download(id);
    }

    @PutMapping ("/move/{fileId}/{tagId}")
     public Result<?> move(@PathVariable String fileId, @PathVariable Long tagId) {
        fileService.changeTag(fileId, tagId);
        return Result.success();
    }

    @Operation(summary = "文件删除")
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable String id) {
        return fileService.delete(id);
    }

    @Operation(summary = "文件彻底删除")
    @DeleteMapping("/deleteCompletely/{id}")
    public Result<String> deleteCompletely(@PathVariable String id) {
        return fileService.deleteCompletely(id);
    }

    @Operation(summary = "文件恢复")
    @PutMapping("/restore/{id}")
    public Result<String> restore(@PathVariable String id) {
        return fileService.restore(id);
    }

}
